<?php

namespace Modules\Wechat\Model\Data\Message;

use Modules\Wechat\Model\Dao\Db\WcMsgExchange;

/**
 * 公众号与用户交互消息的记录
 *
 * @package Modules\Wechat\Model\Data\Message
 */
class Exchange extends \Modules\Wechat\Model\Data\Abstraction
{

    const MSG_TYPE_EMPTY   = 'empty';
    const MSG_TYPE_SUCCESS = 'success';

    protected static $dictionaries = [
        self::DICT_SCOPE_MSG_TYPE => [
            [self::DICT_ENTRY_ID => self::MSG_TYPE_TEXT, self::DICT_ENTRY_VALUE => '文本消息'],
            [self::DICT_ENTRY_ID => self::MSG_TYPE_IMAGE, self::DICT_ENTRY_VALUE => '图片消息'],
            [self::DICT_ENTRY_ID => self::MSG_TYPE_VOICE, self::DICT_ENTRY_VALUE => '语音消息'],
            [self::DICT_ENTRY_ID => self::MSG_TYPE_VIDEO, self::DICT_ENTRY_VALUE => '视频消息'],
            [self::DICT_ENTRY_ID => self::MSG_TYPE_SHORT_VIDEO, self::DICT_ENTRY_VALUE => '小视频消息'],
            [self::DICT_ENTRY_ID => self::MSG_TYPE_LOCATION, self::DICT_ENTRY_VALUE => '地理位置消息'],
            [self::DICT_ENTRY_ID => self::MSG_TYPE_LINK, self::DICT_ENTRY_VALUE => '链接消息'],
            [self::DICT_ENTRY_ID => self::MSG_TYPE_EVENT, self::DICT_ENTRY_VALUE => '事件消息'],
            [self::DICT_ENTRY_ID => self::MSG_TYPE_EMPTY, self::DICT_ENTRY_VALUE => '空消息'],
            [self::DICT_ENTRY_ID => self::MSG_TYPE_SUCCESS, self::DICT_ENTRY_VALUE => '默认成功(success)'],
        ],
    ];

    protected function init()
    {
        return $this;
    }

    public function add($official_account, $type, $from, $to, $time_sent, $message_json)
    {
        $Exchange = new WcMsgExchange;

        $Exchange->official_account = trim($official_account);
        $Exchange->type             = $type;
        $Exchange->from             = $from;
        $Exchange->to               = $to;
        $Exchange->stime            = intval($time_sent);
        $Exchange->msg_json         = $message_json;
        $Exchange->ctime            = time();

        return $Exchange->add();
    }

    /**
     * 以微信发来的消息新建记录
     *
     * @param \EasyWeChat\Message\AbstractMessage $message_request
     *
     * @return bool|int
     */
    public function addByMessageRequest($message_request)
    {
        return $this->add(
            $message_request->ToUserName,
            $message_request->MsgType,
            $message_request->FromUserName,
            $message_request->ToUserName,
            $message_request->CreateTime,
            $message_request->toJson()
        );
    }

    /**
     * 以响应给微信服务器的消息创建记录
     *
     * @param \EasyWeChat\Message\AbstractMessage $message_response
     *
     * @return bool|int
     */
    public function addByMessageResponse($message_response)
    {
        return $this->add(
            $message_response->FromUserName,
            $message_response->MsgType,
            $message_response->FromUserName,
            $message_response->ToUserName,
            $message_response->CreateTime,
            $message_response->toJson()
        );
    }

    /**
     * 获取消息列表
     *
     * 往来消息记录表会非常长,暂时不支持无条件的查询.如果业务线有需要可以自己去实现.
     *
     * @param string $official_account
     * @param string $type
     * @param string $from
     * @param string $to
     *
     * @return array
     */
    public function getList(
        $official_account = '',
        $type = '',
        $from = '',
        $to = '',
        $time_send_start = 0,
        $time_send_end = 0
    ) {
        if (!func_get_args()) {
            return [];
        }
        if (!is_numeric($time_send_start)) {
            $time_send_start = strtotime($time_send_start) ?: 0;
        }
        if (!is_numeric($time_send_end)) {
            $time_send_end = strtotime($time_send_end) ?: 0;
        }
        $list = (new WcMsgExchange)->getList($official_account, $type, $from, $to, $time_send_start, $time_send_end);
        foreach ($list as &$item) {
            $item = $this->processData($item);
        }
        return $list;
    }

    public static function getMsgTypeList($selected_id = '')
    {
        $list = static::dictGetList(static::DICT_SCOPE_MSG_TYPE, []);
        foreach ($list as &$item) {
            $item['selected'] = $selected_id && $selected_id == $item[static::DICT_ENTRY_ID];
        }
        return $list;
    }

    protected function processData(array $data)
    {
        $data['msg']          = json_decode($data['msg_json'], true);
        $data['stime_YmdHis'] = date('Y-m-d H:i:s', $data['stime']);
        $data['content']      = isset($data['msg']['Content'])
            ? $data['msg']['Content']
            : $data['msg']['content'];
        $data['type_name']    = static::getMsgTypeName($data['type']);
        return $data;
    }
}